from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import get_db
from models import Permission, User
from schemas import PermissionCreate, PermissionUpdate, PermissionSchema, ResponseModel, PaginatedResponse
from api.deps import get_current_active_user, get_current_superuser

router = APIRouter()

@router.get("", response_model=ResponseModel[PaginatedResponse[PermissionSchema]])
def get_permissions(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="权限名称搜索"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """获取权限列表"""
    query = db.query(Permission)
    
    if name:
        query = query.filter(Permission.name.contains(name))
    
    # 计算总数
    total = query.count()
    
    # 分页
    permissions = query.offset((page - 1) * page_size).limit(page_size).all()
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=permissions
        )
    )

@router.get("/{permission_id}", response_model=ResponseModel[PermissionSchema])
def get_permission(
    permission_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """获取权限详情"""
    permission = db.query(Permission).filter(Permission.id == permission_id).first()
    if not permission:
        raise HTTPException(
            status_code=404,
            detail="权限不存在"
        )
    
    return ResponseModel(data=permission)

@router.post("", response_model=ResponseModel[PermissionSchema])
def create_permission(
    permission_in: PermissionCreate,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """创建权限"""
    # 检查权限名是否已存在
    permission = db.query(Permission).filter(Permission.name == permission_in.name).first()
    if permission:
        raise HTTPException(
            status_code=400,
            detail="权限名已存在"
        )
    
    # 创建新权限
    db_permission = Permission(
        name=permission_in.name,
        description=permission_in.description
    )
    
    db.add(db_permission)
    db.commit()
    db.refresh(db_permission)
    
    return ResponseModel(data=db_permission)

@router.put("/{permission_id}", response_model=ResponseModel[PermissionSchema])
def update_permission(
    permission_id: int,
    permission_in: PermissionUpdate,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """更新权限"""
    permission = db.query(Permission).filter(Permission.id == permission_id).first()
    if not permission:
        raise HTTPException(
            status_code=404,
            detail="权限不存在"
        )
    
    # 检查权限名是否已存在（排除当前权限）
    if permission_in.name and permission_in.name != permission.name:
        existing_permission = db.query(Permission).filter(Permission.name == permission_in.name).first()
        if existing_permission:
            raise HTTPException(
                status_code=400,
                detail="权限名已存在"
            )
    
    # 更新字段
    update_data = permission_in.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(permission, field, value)
    
    db.commit()
    db.refresh(permission)
    
    return ResponseModel(data=permission)

@router.delete("/{permission_id}", response_model=ResponseModel[dict])
def delete_permission(
    permission_id: int,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """删除权限"""
    permission = db.query(Permission).filter(Permission.id == permission_id).first()
    if not permission:
        raise HTTPException(
            status_code=404,
            detail="权限不存在"
        )
    
    # 检查是否有角色使用该权限
    if permission.roles:
        raise HTTPException(
            status_code=400,
            detail="该权限正在被角色使用，无法删除"
        )
    
    db.delete(permission)
    db.commit()
    
    return ResponseModel(data={"message": "权限删除成功"})